package com.elf.zero.form;

import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;

import androidx.appcompat.app.AlertDialog;

import java.util.ArrayList;
import java.util.List;

public class FormSelect extends FormTextView {

    private List<FormOption> options = new ArrayList<>();
    private FormOption selectedOption;

    public FormSelect(Context context) {
        super(context);
    }

    public FormSelect(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void initView(AttributeSet attrs) {
        super.initView(attrs);

        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.FormSelect);
            boolean mustShow = typedArray.getBoolean(R.styleable.FormSelect_form_must, true);
            tv_must.setVisibility(mustShow ? VISIBLE : GONE);
            typedArray.recycle();
        }

        findViewById(R.id.iv_navigate).setVisibility(VISIBLE);
        findViewById(R.id.layout_root).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectDialog();
            }
        });
    }

    public void setOptions(List<FormOption> options) {
        this.options = options;
    }

    @Override
    public void setValue(String value) {
        for (FormOption option : options) {
            if (option.value.equals(value)) {
                selectedOption = option;
                super.setValue(option.name);
            }
        }
    }

    @Override
    public String getValue() {
        return selectedOption == null ? "" : selectedOption.value;
    }

    public FormOption getSelectedOption() {
        return selectedOption;
    }

    public void setSelectedOption(FormOption option) {
        selectedOption = option;
        super.setValue(selectedOption.name);
    }

    public void showSelectDialog() {
        if (options == null || options.size() == 0) {
            showToast("无可用数据");
            return;
        }

        String[] texts = new String[options.size()];
        for (int i = 0; i < texts.length; i++) {
            texts[i] = options.get(i).name;
        }

        new AlertDialog.Builder(getContext())
                .setItems(texts, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        selectedOption = options.get(which);
                        txt_value.setText(selectedOption.name);
                    }
                }).show();
    }
}
